package com.wuyi.tea.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.wuyi.tea.domain.dto.OrderDTO;
import com.wuyi.tea.domain.pojo.*;
import com.wuyi.tea.domain.vo.OrderDetailVO;
import com.wuyi.tea.domain.vo.OrderVO;
import com.wuyi.tea.domain.vo.ProductVO;
import com.wuyi.tea.mapper.*;
import com.wuyi.tea.service.OrderService;
import com.wuyi.tea.util.LocalStorageUtil;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

@Service
public class OrderServiceImpl extends ServiceImpl<OrderMapper, Order> implements OrderService {

    @Resource
    private UserMapper userMapper;

    @Resource
    private OrderMapper orderMapper;
    @Resource
    private ProductMapper productMapper;
    @Resource
    private OrderProductMapper orderProductMapper;
    @Resource
    private AddressMapper addressMapper;


    @Override
    public Page<OrderVO> getAdminOrderList(Integer page, Integer pageSize) {
        Page<Order> orderPage = orderMapper.selectPage(new Page<>(page, pageSize), null);
        List<OrderVO>orderVOS=new ArrayList<>();

        for (Order order : orderPage.getRecords()) {
            Address address = addressMapper.selectById(order.getAddressId());
            OrderVO orderVO = BeanUtil.copyProperties(order,OrderVO.class);
            orderVO.setUserName(address.getUserName());
            orderVO.setAddress(address);

            double totalPrice = 0;
            List<OrderProduct> orderProducts = orderProductMapper.selectList(new LambdaQueryWrapper<OrderProduct>()
                    .eq(OrderProduct::getOrderId, order.getId())
            );
            for (OrderProduct orderProduct : orderProducts) {
                Product product = productMapper.selectById(orderProduct.getProductId());
                totalPrice+=orderProduct.getProductCount() * product.getPrice();
            }
            orderVO.setTotalPrice(totalPrice);
            orderVOS.add(orderVO);
        }
        Page<OrderVO> resPage = new Page<>(page,pageSize,orderPage.getTotal());
        resPage.setRecords(orderVOS);
        return resPage;
    }

    @Override
    public OrderDetailVO getOrderDetail(Long orderId) {

        OrderDetailVO orderDetailVO = new OrderDetailVO();
        // 1.获取订单基本信息
        Order order = orderMapper.selectById(orderId);
        BeanUtils.copyProperties(order,orderDetailVO);

        // 2.获取地址信息
        Address address = addressMapper.selectById(order.getAddressId());
        orderDetailVO.setAddress(address);

        //获取用户名称
        orderDetailVO.setUserName(address.getUserName());

        // 3.获取购买的商品信息
        //   3.1 获取当前订单所有商品的id
        List<OrderProduct> orderProducts = orderProductMapper.selectList(
                new LambdaQueryWrapper<OrderProduct>()
                        .eq(OrderProduct::getOrderId,orderId)
        );

        double totalPrice = 0;
        //   3.2 通过id获取商品的基本信息
        List<ProductVO>productVOS=new ArrayList<>();
        for (OrderProduct orderProduct : orderProducts) {
            Product product = productMapper.selectById(orderProduct.getProductId());
            ProductVO productVO= BeanUtil.copyProperties(product,ProductVO.class);
            productVO.setCount(orderProduct.getProductCount());
            productVO.setTotalPrice(orderProduct.getProductCount()*product.getPrice());
            productVOS.add(productVO);
            totalPrice += product.getPrice() * orderProduct.getProductCount();
        }
        orderDetailVO.setTotalPrice(totalPrice);
        orderDetailVO.setProducts(productVOS);

        return orderDetailVO;
    }

    @Transactional
    @Override
    public void addOrder(OrderDTO orderDTO) {

        if (orderDTO.getAddressId()==null||orderDTO.getPayStatus()==null){
            throw new RuntimeException("请检查传递的数据是否完整");
        }
        for (OrderProduct product : orderDTO.getProducts()) {
            if (product.getId()!=null){
                product.setProductId(product.getId());
            }

            if (product.getProductId()==null||product.getProductCount()==null){
                throw new RuntimeException("请检查传递的数据是否完整");
            }
        }

        // 1. 获取当前用户id
        Long userId = Long.valueOf(LocalStorageUtil.get().toString());
        orderDTO.setUserId(userId);

        // 2. 添加到订单表
        Order order = BeanUtil.copyProperties(orderDTO,Order.class);
        orderMapper.insert(order);

        orderDTO.setId(order.getId());  //  记录订单id
        // 3. 添加到订单与商品的关联表
        List<OrderProduct> orderProductList = orderDTO.getProducts();

        for (OrderProduct orderProduct : orderProductList) {
            orderProduct.setOrderId(order.getId());
            // 添加到订单与商品的关联表
            orderProductMapper.insert(orderProduct);
        }
    }

    @Transactional
    @Override
    public void deleteOrder(Long orderId) {

        // 1.删除与该订单相关的所有商品
        orderProductMapper.delete(new LambdaQueryWrapper<OrderProduct>()
                        .eq(OrderProduct::getOrderId,orderId)
        );

        // 2.删除订单
        orderMapper.deleteById(orderId);
    }

    @Override
    public List<OrderDetailVO> listNeedPay() {
        List<OrderDetailVO> allList = getAllList();
        List<OrderDetailVO> res = new ArrayList<>();
        for (OrderDetailVO orderDetailVO : allList) {
            if (orderDetailVO.getPayStatus().equals(0)){
                res.add(orderDetailVO);
            }
        }
        return res;
    }

    @Override
    public List<OrderDetailVO> listAlReadyPay() {
        List<OrderDetailVO> allList = getAllList();
        List<OrderDetailVO> res = new ArrayList<>();
        for (OrderDetailVO orderDetailVO : allList) {
            if (orderDetailVO.getPayStatus().equals(1)){
                res.add(orderDetailVO);
            }
        }
        return res;
    }

    @Override
    public List<OrderVO> getList() {
        // 拿到用户
        User user = userMapper.selectById(LocalStorageUtil.get().toString());

        List<Order> orders = orderMapper.selectList(null);
        List<OrderVO> orderVOS = new ArrayList<>();
        for (Order order : orders) {
            OrderVO orderVO = BeanUtil.copyProperties(order,OrderVO.class);

            Address address = addressMapper.selectById(order.getAddressId());
            orderVO.setUserName(address.getUserName());
            //  查询出当前订单相关的所有商品id
            List<OrderProduct> orderProducts = orderProductMapper.selectList(new LambdaQueryWrapper<OrderProduct>()
                    .eq(OrderProduct::getOrderId, order.getId())
            );
            double totalPrice = 0;
            // 拿到所有商品
            for (OrderProduct orderProduct : orderProducts) {

                Product product = productMapper.selectById(orderProduct.getProductId());
                totalPrice += product.getPrice() * orderProduct.getProductCount();
            }
            orderVO.setTotalPrice(totalPrice);

            orderVOS.add(orderVO);
        }
        return orderVOS;
    }

    @Override
    public List<OrderDetailVO> getAllList() {
        User user = userMapper.selectById(LocalStorageUtil.get().toString());

        List<Order> orders = orderMapper.selectList(new LambdaQueryWrapper<Order>()
                .eq(Order::getUserId,user.getId()));


        List<OrderDetailVO> detailVOList=new ArrayList<>();

        for (Order order : orders) {
            List<ProductVO> productslist=new ArrayList<>();
            OrderDetailVO orderDetailVO = BeanUtil.copyProperties(order, OrderDetailVO.class);
            Address address = addressMapper.selectById(order.getAddressId());
            orderDetailVO.setAddress(address);
            orderDetailVO.setUserName(address.getUserName());
            //  查询出当前订单相关的所有商品id
            List<OrderProduct> orderProducts = orderProductMapper.selectList(new LambdaQueryWrapper<OrderProduct>()
                    .eq(OrderProduct::getOrderId, order.getId())
            );
            double totalPrice = 0;
            // 拿到所有商品
            for (OrderProduct orderProduct : orderProducts) {

                Product product = productMapper.selectById(orderProduct.getProductId());
                totalPrice += product.getPrice() * orderProduct.getProductCount();

                //
                ProductVO productVO = BeanUtil.copyProperties(product, ProductVO.class);
                productVO.setCount(orderProduct.getProductCount());

                productslist.add(productVO);
            }

            orderDetailVO.setProducts(productslist);
            orderDetailVO.setTotalPrice(totalPrice);

            detailVOList.add(orderDetailVO);
        }
        return detailVOList;
    }
}
